package service.impl;

import dao.CartDao;
import dao.OrderDao;
import dao.impl.CartDaoImpl;
import dao.impl.OrderDaoImpl;
import entity.Cart;
import entity.Item;
import entity.Orders;
import service.OrderService;
import util.RandomUtils;

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @version 1.0
 * @Author: xxf
 * @CreateDate: 2020/10/7 19:25
 */
public class OrderServiceImpl implements OrderService {

    private OrderDao orderDao = new OrderDaoImpl();

    /**
     * 根据用户id，总金额和地址id创建订单
     * @param uid
     * @param aid
     * @param sum
     */
    @Override
    public void createOrder(int uid, int aid, String sum) throws InvocationTargetException, IllegalAccessException {

        //创建订单对象并对其属性赋值
        String orderId = RandomUtils.createOrderId();
        //订单默认未支付状态
        Orders orders = new Orders(orderId,uid,aid,new BigDecimal(sum),new Date());

        //调用dao保存订单
        orderDao.addOrders(orders);

        //将购物车转成订单项item
        CartDao cartDao = new CartDaoImpl();
        List<Cart> cartList = cartDao.findCartByUid(uid);

        List<Item> items = new ArrayList<>();
        for (Cart cart : cartList) {
            Item item = new Item(orderId, cart.getPid(), cart.getCcount(), cart.getCnum());
            items.add(item);
        }

        //保存订单对应的订单项
        orderDao.addItems(items);
        //清空购物车
        cartDao.deleteCartByUid(uid);
    }

    /**
     * 根据uid查询订单
     * @param uid
     * @return
     */
    @Override
    public List<Orders> findOrdersByUid(int uid) throws InvocationTargetException, IllegalAccessException {
        return orderDao.findOrdersByUid(uid);
    }

    @Override
    public Orders findOrdersByOid(String oid) throws InvocationTargetException, IllegalAccessException {

        //查询订单（订单地址）获得订单对象
        Orders orders = orderDao.findOrdersByOid(oid);
        //查询订单项和商品信息获得订单项集合
        List<Item> items = orderDao.findItemsByOid(oid);
        //订单项集合传入订单对象中
        orders.setItems(items);
        return orders;
    }

    /**
     * 根据oid修改支付状态
     * @param oid
     */
    @Override
    public void updateOrderStateByOid(String oid) {
        orderDao.updateOrderStateByOid(oid);
    }
}
